/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ee.ut.math.esi.service;

import java.util.Set;
import java.util.TreeSet;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author ool
 */
public class AlchemyApiResponseService {

    private static String STATE_OR_COUNTRY = "StateOrCounty";
    private static String CITY = "City";
    private static String TYPE_NODE_NAME = "type";
    private static String TEXT_NODE_NAME = "text";

    public static Set<String> getLocationsFromAlchemyAPIResult(Node rootNode) {

        NodeList list = rootNode.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            Node node = list.item(i);
            if ("entities".equals(node.getNodeName())) {
                return getLocationsFromEntityNodes(node);
            }
        }
        return new TreeSet<String>();
    }

    private static Set<String> getLocationsFromEntityNodes(Node entitiesNode) {
        Set<String> result = new TreeSet<String>();
        NodeList entities = entitiesNode.getChildNodes();
        for (int i = 0; i < entities.getLength(); i++) {
            String location = getLocationNameFromEntity(entities.item(i));
            if (location != null) {
                result.add(location);
            }
        }
        return result;
    }

    private static String getLocationNameFromEntity(Node entity) {
        NodeList entityChildren = entity.getChildNodes();
        boolean isLocation = false;
        String result = null;
        for (int i = 0; i < entityChildren.getLength(); i++) {
            Node node = entityChildren.item(i);
            if (TEXT_NODE_NAME.equals(node.getNodeName())) {
                result = node.getTextContent();
            } else if (TYPE_NODE_NAME.equals(node.getNodeName())) {
                String type = node.getTextContent();
                if (CITY.equals(type) || STATE_OR_COUNTRY.equals(type)) {
                    isLocation = true;
                }
            }

        }
        return isLocation ? result : null;
    }
}
